package com.ruoyi.exam.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.Collections;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.exam.domain.entity.Question;
import com.ruoyi.exam.domain.entity.TWrongQuestion;
import com.ruoyi.exam.domain.vo.QuestionImportVo;
import com.ruoyi.exam.mapper.QuestionMapper;
import com.ruoyi.exam.mapper.TWrongQuestionMapper;
import com.ruoyi.exam.service.IQuestionService;

/**
 * 题目，存储题目信息Service业务层处理
 */
@Service
public class QuestionServiceImpl implements IQuestionService {

    private static final Logger log = LoggerFactory.getLogger(QuestionServiceImpl.class);

    // 使用ConcurrentHashMap来存储正在处理的文件名
    private static final Map<String, Boolean> PROCESSING_FILES = new ConcurrentHashMap<>();

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private TWrongQuestionMapper tWrongQuestionMapper;

    @Override
    public Question selectQuestionById(Long id) {
        return questionMapper.selectQuestionById(id);
    }

    @Override
    public List<Question> selectQuestionList(Question question) {
        return questionMapper.selectQuestionList(question);
    }

    @Override
    public int insertQuestion(Question question) {
        // 根据题干查询是否存在相同题目
        Question params = new Question();
        params.setQuestionTitle(question.getQuestionTitle());
        params.setOutline(question.getOutline());
        List<Question> existingQuestions = questionMapper.selectQuestionList(params);

        // 如果存在相同题干的题目，则不插入
        if (!existingQuestions.isEmpty()) {
            return 0;
        }

        return questionMapper.insertQuestion(question);
    }

    @Override
    public int updateQuestion(Question question) {
        question.setUpdateTime(DateUtils.getNowDate());
        return questionMapper.updateQuestion(question);
    }

    @Override
    @Transactional
    public int deleteQuestionByIds(Long[] ids) {
        int row = 0;
        for (Long id : ids) {
            row = row + deleteQuestionById(id);
        }
        return row;
    }

    @Override
    @Transactional
    public int deleteQuestionById(Long id) {
        // 1. 删除关联的错题记录
        TWrongQuestion wrongQuestion = new TWrongQuestion();
        wrongQuestion.setQuestionId(id);
        List<TWrongQuestion> wrongQuestions = tWrongQuestionMapper.selectTWrongQuestionList(wrongQuestion);
        if (!wrongQuestions.isEmpty()) {
            Long[] wrongIds = wrongQuestions.stream()
                    .map(TWrongQuestion::getId)
                    .toArray(Long[]::new);
            tWrongQuestionMapper.deleteTWrongQuestionByIds(wrongIds);
        }
        // 2. 删除题目
        return questionMapper.deleteQuestionById(id);
    }

    @Override
    @Transactional
    public String importQuestion(List<QuestionImportVo> importList, String outline) {
        // 检查文件是否正在处理
        if (PROCESSING_FILES.putIfAbsent(outline, true) != null) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", 0);
            result.put("failure", 1);
            result.put("total", 1);
            result.put("errors", Arrays.asList("该文件正在处理中，请稍后再试"));
            return JSON.toJSONString(result);
        }

        try {
            if (StringUtils.isNull(importList) || importList.size() == 0) {
                throw new ServiceException("导入试题数据不能为空！");
            }
            int successNum = 0;
            int failureNum = 0;
            List<String> errorDetails = new ArrayList<>();

            // 统计不同题型的数量
            Map<String, Integer> typeCount = new HashMap<>();
            typeCount.put("其他", 0);

            for (QuestionImportVo vo : importList) {
                try {
                    Question question = new Question();
                    BeanUtils.copyProperties(vo, question);
                    question.setOutline(outline);

                    // 根据题干和题目查询是否存在相同题目
                    Question params = new Question();
                    params.setQuestionTitle(question.getQuestionTitle());
                    params.setOutline(outline);
                    List<Question> existingQuestions = questionMapper.selectQuestionList(params);

                    // 如果存在相同题干的相同题目，则跳过并记录失败信息
                    if (!existingQuestions.isEmpty()) {
                        failureNum++;
                        errorDetails.add("题目已存在，题库：" + outline + "，题干：" + question.getQuestionTitle());
                        continue;
                    }

                    // 设置题型
                    Long questionType = convertQuestionType(vo.getQuestionTypeName());
                    if (questionType == null) {
                        typeCount.put("其他", typeCount.get("其他") + 1);
                        continue;
                    }
                    question.setQuestionType(questionType);

                    // 处理选项
                    List<Map<String, String>> options = parseOptions(vo.getOptions());
                    
                    // 过滤没有选项内容的异常数据
                    if (options.isEmpty() || hasEmptyOptions(options)) {
                        failureNum++;
                        errorDetails.add("题目选项内容不完整，题库：" + outline + "，题干：" + question.getQuestionTitle());
                        continue;
                    }
                    
                    question.setQuestionText(JSON.toJSONString(options));

                    // 设置答案
                    if (question.getQuestionType() == 2L) { // 多选题
                        // 将 "A,B,C" 或 "ABC" 转换为 ["A","B","C"]
                        String answer = vo.getAnswer().trim();
                        String[] answers;
                        if (answer.contains(",")) {
                            answers = answer.split(",");
                        } else {
                            // 如果是连续的字母，将其拆分为单个字符
                            answers = answer.split("");
                        }
                        // 去除每个答案的空格
                        for (int i = 0; i < answers.length; i++) {
                            answers[i] = answers[i].trim();
                        }
                        // 创建List<String>确保JSON序列化时每个元素都是字符串
                        List<String> answerList = new ArrayList<>();
                        for (String ans : answers) {
                            answerList.add(ans);
                        }
                        question.setQuestionAnswer(JSON.toJSONString(answerList));
                    } else {
                        // 单选题和判断题去除答案中的空格
                        question.setQuestionAnswer(vo.getAnswer().trim());
                    }

                    question.setQuestionAnswerExplain(vo.getQuestionAnswerExplain());
                    // 按照题型设置分数
                    if (question.getQuestionType() == 1L) { // 单选
                        question.setQuestionScore(1.0);
                    } else if (question.getQuestionType() == 2L) { // 多选
                        question.setQuestionScore(2.0);
                    } else if (question.getQuestionType() == 3L) { // 判断
                        question.setQuestionScore(0.5);
                    }

                    // 插入数据库
                    if (insertQuestion(question) > 0) {
                        successNum++;
                    } else {
                        failureNum++;
                        errorDetails.add("题目已存在，题库：" + outline + "，题干：" + question.getQuestionTitle());
                    }
                } catch (Exception e) {
                    failureNum++;
                    errorDetails.add("导入异常：" + e.getMessage());
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("success", successNum);
            result.put("failure", failureNum);
            result.put("total", importList.size());
            result.put("errors", errorDetails);

            return JSON.toJSONString(result);
        } finally {
            // 处理完成后移除文件锁
            PROCESSING_FILES.remove(outline);
        }
    }

    /**
     * 转换题型名称为题型ID
     * 如果是未知题型返回null
     */
    private Long convertQuestionType(String typeName) {
        switch (typeName) {
            case "单选题":
                return 1L;
            case "多选题":
                return 2L;
            case "判断题":
                return 3L;
            default:
                return null;
        }
    }

    /**
     * 解析选项文本为选项列表
     */
    private List<Map<String, String>> parseOptions(String optionsStr) {
        List<Map<String, String>> options = new ArrayList<>();
        if (StringUtils.isEmpty(optionsStr)) {
            return options;
        }

        String[] optionArr = optionsStr.split("\\|");

        for (String option : optionArr) {
            if (StringUtils.isNotEmpty(option.trim())) {
                // 分割选项前缀和内容 (例如: "A-党政同责" -> ["A", "党政同责"])
                String[] parts = option.trim().split("-", 2);
                if (parts.length == 2) {
                    Map<String, String> map = new HashMap<>();
                    map.put("prefix", parts[0].trim());
                    map.put("content", parts[1].trim());
                    options.add(map);
                }
            }
        }
        return options;
    }

    /**
     * 检查选项是否有空内容
     */
    private boolean hasEmptyOptions(List<Map<String, String>> options) {
        return options.stream().anyMatch(option -> 
            StringUtils.isEmpty(option.get("prefix")) || 
            StringUtils.isEmpty(option.get("content"))
        );
    }

    @Override
    public List<Question> generatePaperQuestions(List<String> titleNames, Map<String, Integer> typeCount) {
        List<Question> result = new ArrayList<>();

        // 根据题库名称获取所有可用题目
        List<Question> availableQuestions = questionMapper.selectQuestionsByOutlines(titleNames);

        // 按题型分组
        Map<Long, List<Question>> questionsByType = availableQuestions.stream()
                .collect(Collectors.groupingBy(Question::getQuestionType));

        // 为每种题型随机选择指定数量的题目
        typeCount.forEach((type, count) -> {
            List<Question> typeQuestions = questionsByType.get(Long.parseLong(type));
            if (typeQuestions != null && !typeQuestions.isEmpty()) {
                // 随机打乱题目顺序
                Collections.shuffle(typeQuestions);
                // 选择指定数量的题目
                result.addAll(typeQuestions.stream()
                        .limit(count)
                        .collect(Collectors.toList()));
            }
        });

        return result;
    }
}
